package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化过滤器
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        // 获取请求的URI
        String uri = request.getRequestURI();
        
        // 不需要过滤的资源
        if(uri.contains("/login.jsp") || 
           uri.contains("/register.jsp") || 
           uri.contains("/css/") || 
           uri.contains("/js/") || 
           uri.contains("/images/") ||
           uri.contains("/fonts/") ||
           uri.contains("/LoginServlet") ||
           uri.contains("/RegisterServlet")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 获取session中的登录标记
        Object user = session.getAttribute("user");
        Object admin = session.getAttribute("admin");

        // 如果未登录，重定向到登录页面
        if(user == null && admin == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        } else {
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        // 销毁过滤器
    }
}
